# !/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Pro数据接口 
Created on 2021/02/22
@author: weilaihui
"""
import pandas as pd
import json
from functools import partial
import requests
from datetime import datetime, date, timedelta

class ClientApi:

    __token = ''
    __http_url = 'http://localhost:8000/stock/all/'

    def __init__(self, token, timeout=15):
        """
        Parameters
        ----------
        token: str
            API接口TOKEN，用于用户认证
        """
        self.__token = token
        self.__timeout = timeout

    def query(self, api_name, fields='', **kwargs):
        req_params = {
            'api_name': api_name,
            'token': self.__token,
            'params': kwargs,
            'fields': fields
        }

        res = requests.post(self.__http_url, json=req_params, timeout=self.__timeout, headers={'Connection':'close'})
        if res:
            result = json.loads(res.text)
            if result['code'] != 200:
                raise Exception(result['msg'])
            data = result['data']
            columns = data['fields']
            items = data['items']
            return pd.DataFrame(items, columns=columns)
        else:
            return pd.DataFrame()

    def __getattr__(self, name):
        return partial(self.query, name)

if __name__ == '__main__':
    api = ClientApi('token')
    now = datetime.now()
    start_dt = now - timedelta(days=1)
    
    start_date = start_dt.strftime('%Y%m%d')
    end_date = now.strftime('%Y%m%d')

    df = api.daily(start_date=start_date, end_date=end_date)
    print(df)